import base64
import urllib
import requests
import json
import os
from config import BAIDU_SPEECH_CONFIG

API_KEY = BAIDU_SPEECH_CONFIG['API_KEY']
SECRET_KEY = BAIDU_SPEECH_CONFIG['SECRET_KEY']

def main(file_path):
    
        
    url = "https://vop.baidu.com/server_api"
    
    # speech 可以通过 get_file_content_as_base64("C:\fakepath\16k.wav",False) 方法获取
    payload = json.dumps({
    "format":"wav",
    "rate":8000,
    "dev_pid":1537,
    "channel":1,
    "token":get_access_token(),
    "len": get_audio_file_byte_size(file_path),
    "cuid": "3dSGVfMbAYnHkiAjZiG8nCMoXk6XYYYh",
    "speech":get_file_content_as_base64(file_path), # get_file_content_as_base64("C:\fakepath\16k.wav",False)
})
    headers = {
        
        'Content-Type': 'wav/mp3;rate=16000',
        
        
        
    }
    
    response = requests.request("POST", url, headers=headers, data=payload)
    return response.text
    
    
    
def get_audio_file_byte_size(file_path):
    if os.path.exists(file_path):
        print(os.path.getsize(file_path))
        return os.path.getsize(file_path)
    else:
        return "文件不存在"
def get_file_content_as_base64(path, urlencoded=False):
    """
    获取文件base64编码
    :param path: 文件路径
    :param urlencoded: 是否对结果进行urlencoded 
    :return: base64编码信息
    """
    with open(path, "rb") as f:
        content = base64.b64encode(f.read()).decode("utf8")
        if urlencoded:
            content = urllib.parse.quote_plus(content)
        
    return content

def get_access_token():
    """
    使用 AK，SK 生成鉴权签名（Access Token）
    :return: access_token，或是None(如果错误)
    """
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
    return str(requests.post(url, params=params).json().get("access_token"))

if __name__ == '__main__':
    print(main("./audio/received_audio.wav"))
